// Script to copy static assets to dist folder after build
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function copyRecursiveSync(src, dest) {
  const exists = fs.existsSync(src);
  const stats = exists && fs.statSync(src);
  const isDirectory = exists && stats.isDirectory();
  
  if (isDirectory) {
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true });
    }
    fs.readdirSync(src).forEach(childItemName => {
      copyRecursiveSync(
        path.join(src, childItemName),
        path.join(dest, childItemName)
      );
    });
  } else {
    fs.copyFileSync(src, dest);
  }
}

const distDir = path.resolve(__dirname, '../dist');
const dataSrc = path.resolve(__dirname, '../data');
const iconsSrc = path.resolve(__dirname, '../icons');
const manifestSrc = path.resolve(__dirname, '../manifest.json');
const dataDest = path.join(distDir, 'data');
const iconsDest = path.join(distDir, 'icons');
const manifestDest = path.join(distDir, 'manifest.json');

// Copy data directory
if (fs.existsSync(dataSrc)) {
  copyRecursiveSync(dataSrc, dataDest);
  console.log('✓ Copied data directory');
}

// Copy icons directory
if (fs.existsSync(iconsSrc)) {
  copyRecursiveSync(iconsSrc, iconsDest);
  console.log('✓ Copied icons directory');
}

// Copy and fix manifest.json (remove dist/ prefix from paths)
if (fs.existsSync(manifestSrc)) {
  const manifestContent = fs.readFileSync(manifestSrc, 'utf8');
  const manifest = JSON.parse(manifestContent);
  
  // Remove 'dist/' prefix from all paths
  if (manifest.background && manifest.background.service_worker) {
    manifest.background.service_worker = manifest.background.service_worker.replace(/^dist\//, '');
  }
  if (manifest.action && manifest.action.default_popup) {
    manifest.action.default_popup = manifest.action.default_popup.replace(/^dist\//, '');
  }
  if (manifest.options_page) {
    manifest.options_page = manifest.options_page.replace(/^dist\//, '');
  }
  
  fs.writeFileSync(manifestDest, JSON.stringify(manifest, null, 2));
  console.log('✓ Copied and fixed manifest.json');
}

console.log('Asset copying complete!');
